package com.cxh.rmsq.ui.activity.self;

import static com.cxh.rmsq.utils.ExtendsKt.loadImage;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cxh.rmsq.R;
import com.cxh.rmsq.common.IntentExtra;
import com.cxh.rmsq.db.model.BaseResultCommentListBean;
import com.cxh.rmsq.db.model.CommentChildren;
import com.cxh.rmsq.db.model.CommunityContent;
import com.cxh.rmsq.im.IMManager;
import com.cxh.rmsq.model.Resource;
import com.cxh.rmsq.model.Resource2;
import com.cxh.rmsq.model.Result2;
import com.cxh.rmsq.model.Status;
import com.cxh.rmsq.net.RetrofitUtil;
import com.cxh.rmsq.net.newNet.BaseResultEntity;
import com.cxh.rmsq.net.newNet.ProjectViewModel;
import com.cxh.rmsq.qrcode.SealQrCodeUISelector;
import com.cxh.rmsq.ui.activity.TitleBaseActivity;
import com.cxh.rmsq.ui.adapter.self.CommentListAdapter;
import com.cxh.rmsq.ui.widget.SelectableRoundedImageView;
import com.cxh.rmsq.utils.GlideEngine;
import com.cxh.rmsq.utils.MyGridView;
import com.cxh.rmsq.utils.MyUtils;
import com.cxh.rmsq.utils.ToastUtils;
import com.cxh.rmsq.utils.dialog.CommentPopup;
import com.cxh.rmsq.utils.log.SLog;
import com.cxh.rmsq.viewmodel.SocialCircleViewModel;
import com.cxh.rmsq.viewmodel.UserInfoViewModel;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.view.ShapeImageView;
import com.hjq.shape.view.ShapeTextView;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.interfaces.XPopupCallback;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.MaterialHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.xuexiang.xui.widget.imageview.RadiusImageView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.rong.imkit.RongIM;
import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import okhttp3.RequestBody;

/**
 * 评论详情
 */
public class CommentDetailActivity extends TitleBaseActivity implements CommentListAdapter.OnCustomClickListener {

    private TextView tvName, tvTime, tvContent, tvCommentCount, tvLikeCount, tvSexAge, tv_like_bottom, tv_comment_bottom, stv_circle, tv_auth_name;
    private SelectableRoundedImageView sivHeader;
    private NestedScrollView nestedscrollview;
    private ImageView iv_like, iv_play, iv_like_bottom, iv_auth_img, sll_vip;
    private ShapeImageView siv_signle_img;
    private LinearLayout ll_bottom, ll_auth;
    private ShapeTextView stv_focus, stv_focused, stv_group_name, stv_comment, stv_top;
    private MyGridView recyclerView;
    private RecyclerView rv_list;
    private SmartRefreshLayout refreshList;

    private SocialCircleViewModel socialCircleViewModel;
    private List<String> mData = new ArrayList<>();

    private CommunityContent communityContent;
    private CommentListAdapter listAdapter;
    private int page = 1, communityUserid;
    private BasePopupView popupView;
    private String commentImg = "";
    private UserInfoViewModel userInfoViewModel;
    private ProjectViewModel viewModel;
    private ShapeLinearLayout sll_circle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_detail);
        tvName = findViewById(R.id.tv_name);
        sivHeader = findViewById(R.id.siv_header);
        tvTime = findViewById(R.id.tv_time);
        tvContent = findViewById(R.id.tv_content);
        tvCommentCount = findViewById(R.id.tv_comment);
        tv_comment_bottom = findViewById(R.id.tv_comment_bottom);
        iv_like_bottom = findViewById(R.id.iv_like_bottom);
        tv_like_bottom = findViewById(R.id.tv_like_bottom);
        tvLikeCount = findViewById(R.id.tv_like);
        tvSexAge = findViewById(R.id.tv_sex_age);
        iv_like = findViewById(R.id.iv_like);
        recyclerView = findViewById(R.id.recyclerView);
        siv_signle_img = findViewById(R.id.siv_signle_img);
        iv_play = findViewById(R.id.iv_play);
        stv_focus = findViewById(R.id.stv_focus);
        stv_focused = findViewById(R.id.stv_focused);
        refreshList = findViewById(R.id.refresh_list);
        rv_list = findViewById(R.id.rv_list);
        stv_group_name = findViewById(R.id.stv_group_name);
        stv_circle = findViewById(R.id.stv_circle);
        sll_circle = findViewById(R.id.sll_circle);
        ll_bottom = findViewById(R.id.ll_bottom);
        stv_comment = findViewById(R.id.stv_comment);
        stv_top = findViewById(R.id.stv_top);
        ll_auth = findViewById(R.id.ll_auth);
        iv_auth_img = findViewById(R.id.iv_auth_img);
        tv_auth_name = findViewById(R.id.tv_auth_name);
        nestedscrollview = findViewById(R.id.nestedscrollview);
        sll_vip = findViewById(R.id.sll_vip);

        ll_bottom.setVisibility(View.GONE);
        nestedscrollview.setVisibility(View.GONE);
        viewModel = ViewModelProviders.of(this).get(ProjectViewModel.class);
        socialCircleViewModel = ViewModelProviders.of(this).get(SocialCircleViewModel.class);
        userInfoViewModel = ViewModelProviders.of(this).get(UserInfoViewModel.class);
        getTitleBar().getTvTitle().setText("详情");
        getTitleBar().getBtnRight().setVisibility(View.VISIBLE);
        getTitleBar().getBtnRight().setImageDrawable(getResources().getDrawable(R.mipmap.icon_three_point_black));
        getTitleBar().getBtnRight().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (IMManager.getInstance().getCurrentId().equals(communityContent.getUserId() + "")) {//是自己
                    titleList.clear();
                    if (communityContent.getTop() == 1) {
                        titleList.add("取消置顶");
                    } else {
                        titleList.add("置顶");
                    }
//                    titleList.add("修改可见范围");
                    titleList.add("删除");
                    new XPopup.Builder(CommentDetailActivity.this)
                            .dismissOnTouchOutside(true)
                            .dismissOnBackPressed(true)
                            .asBottomList("", titleList.toArray(new String[0]), new OnSelectListener() {
                                @Override
                                public void onSelect(int pos, String text) {
                                    if (0 == pos) {
                                        int top = 0;
                                        if (communityContent.getTop() == 1) {
                                            top = 0;
                                        } else {
                                            top = 1;
                                        }
                                        HashMap<String, Object> map = new HashMap<>();
                                        map.put("id", communityContent.getId());
                                        map.put("top", top);//0:不置顶 1:置顶
//                                        map.put("sort", "");
                                        viewModel.topped(map, new Function1<BaseResultEntity<Object>, Unit>() {
                                            @Override
                                            public Unit invoke(BaseResultEntity<Object> result) {
                                                if (result.getCode() == 200) {
                                                    ToastUtils.showToast("设置成功");
                                                    finish();
                                                } else {
                                                    ToastUtils.showToast(result.getMsg());
                                                }
                                                return null;
                                            }
                                        });
                                    } /*else if (1 == pos) {
                                        editVisible();
                                    } */ else if (1 == pos) {
                                        viewModel.deleteCommunity(communityContent.getId() + "", new Function1<BaseResultEntity<Object>, Unit>() {
                                            @Override
                                            public Unit invoke(BaseResultEntity<Object> result) {
                                                if (result.getCode() == 200) {
                                                    ToastUtils.showToast("删除成功成功");
                                                    finish();
                                                } else {
                                                    ToastUtils.showToast(result.getMsg());
                                                }
                                                return null;
                                            }
                                        });
//                                        socialCircleViewModel.delComment(communityContent.getId() + "");
//                                        socialCircleViewModel.delComment().observe(CommentDetailActivity.this, new Observer<Result2<String>>() {
//                                            @Override
//                                            public void onChanged(Result2<String> result) {
//
//                                                if (result.code == 200) {
//                                                    ll_bottom.setVisibility(View.VISIBLE);
//                                                    ToastUtils.showToast("删除成功");
//                                                    if (popupView != null) {
//                                                        popupView.dismiss();
//                                                    }
//                                                    initDate();
//                                                } else {
//                                                    ToastUtils.showToast(result.msg);
//                                                }
////                                    socialCircleViewModel.delComment().removeObserver(this);
//
//                                            }
//                                        });
                                    }
                                }
                            })
                            .show();
                } else {
                    startActivity(new Intent(CommentDetailActivity.this, UserOperateActivity.class)
                            .putExtra(IntentExtra.STR_TARGET_ID, communityContent.getUserId() + "")
                            .putExtra("contentId", communityContent.getId() + "")//社区
                            .putExtra("fromWhere", "community"));
                }
            }
        });
        initView();
        initDate();
        showLoadingDialog("加载中");
        socialCircleViewModel.getCommunityInfo().observe(CommentDetailActivity.this, new Observer<Result2<CommunityContent>>() {
            @Override
            public void onChanged(Result2<CommunityContent> result) {
                dismissLoadingDialog();
                if (result.code == 200) {
                    ll_bottom.setVisibility(View.VISIBLE);
                    nestedscrollview.setVisibility(View.VISIBLE);
                    communityContent = result.data;
                    communityUserid = communityContent.getUserId();
                    tvName.setText(result.data.getNickname());
                    tvTime.setText(TimeUtils.getFriendlyTimeSpanByNow(result.data.getCreateTime()));
                    if (!TextUtils.isEmpty(result.data.getContent())) {
                        tvContent.setText(result.data.getContent());
                        tvContent.setVisibility(View.VISIBLE);
                    } else {
                        tvContent.setVisibility(View.GONE);
                    }
                    if (!TextUtils.isEmpty(result.data.getBirthday())) {
                        tvSexAge.setText(MyUtils.calculateAge2(
                                Integer.parseInt(result.data.getBirthday().split("-")[0]),
                                Integer.parseInt(result.data.getBirthday().split("-")[1]),
                                Integer.parseInt(result.data.getBirthday().split("-")[2])) + "");
                    }

                    tvCommentCount.setText(result.data.getCommentCount() + "");
                    tv_comment_bottom.setText(result.data.getCommentCount() + "");
                    tvLikeCount.setText(result.data.getLikedCount() + "");
                    tv_like_bottom.setText(result.data.getLikedCount() + "");

                    loadImage(result.data.getAvatar(), sivHeader);

                    if (1 == result.getResult().getSex()) {
                        tvSexAge.setCompoundDrawablesWithIntrinsicBounds(
                                getResources().getDrawable(R.mipmap.icon_male),
                                null,
                                null,
                                null
                        );
                        tvSexAge.setBackgroundResource(R.drawable.shape_sex_male_bg);
                    } else {
                        tvSexAge.setCompoundDrawablesWithIntrinsicBounds(
                                getResources().getDrawable(R.mipmap.icon_male),
                                null,
                                null,
                                null
                        );
                        tvSexAge.setBackgroundResource(R.drawable.shape_sex_female_bg);
                    }

                    if (!TextUtils.isEmpty(result.getResult().isLiked() + "") && result.getResult().isLiked() == 1) {
                        iv_like.setImageDrawable(getResources().getDrawable(R.mipmap.icon_cicrle_liked));
                        iv_like_bottom.setImageDrawable(getResources().getDrawable(R.mipmap.icon_cicrle_liked));
                    } else {
                        iv_like.setImageDrawable(getResources().getDrawable(R.mipmap.icon_cicrle_no_like));
                        iv_like_bottom.setImageDrawable(getResources().getDrawable(R.mipmap.icon_cicrle_no_like));
                    }
                    if (result.getResult().getVipLevel() == 0) {//不是会员
                        sll_vip.setVisibility(View.GONE);
                    } else {
                        sll_vip.setVisibility(View.VISIBLE);
                    }

                    if (!TextUtils.isEmpty(result.getResult().getGroupsName())) {
                        stv_group_name.setVisibility(View.VISIBLE);
                        stv_group_name.setText(result.getResult().getGroupsName() + " >");
                        stv_group_name.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (IMManager.getInstance().getCurrentId().equals(result.getResult().getUserId() + "")) {
                                    RongIM.getInstance()
                                            .startGroupChat(CommentDetailActivity.this, result.getResult().getGroupId() + "", result.getResult().getGroupsName());
                                } else {
                                    SealQrCodeUISelector uiSelector = new SealQrCodeUISelector(CommentDetailActivity.this);
                                    MutableLiveData<Resource<String>> results = new MutableLiveData<>();
                                    uiSelector.checkIsInGroup(result.getResult().getGroupId() + "", result.getResult().getGroupsName(), results);
                                }
                            }
                        });

                    } else {
                        stv_group_name.setVisibility(View.GONE);
                    }

                    if (!TextUtils.isEmpty(result.getResult().getCircleName())) {
                        sll_circle.setVisibility(View.VISIBLE);
                        stv_circle.setText(result.getResult().getCircleName());
                    } else {
                        sll_circle.setVisibility(View.GONE);
                    }

                    if (IMManager.getInstance().getCurrentId().equals(communityContent.getUserId() + "")) {
                        stv_focus.setVisibility(View.GONE);
                        stv_focused.setVisibility(View.GONE);
                        ll_auth.setVisibility(View.VISIBLE);
                        if (communityContent.getAuth() == 2) {//
                            iv_auth_img.setImageDrawable(getResources().getDrawable(R.mipmap.icon_trend_order));
                            tv_auth_name.setText("好友可见");
                        } else if (communityContent.getAuth() == 3) {//
                            iv_auth_img.setImageDrawable(getResources().getDrawable(R.mipmap.icon_trend_someone));
                            tv_auth_name.setText("部分可见");
                        } else if (communityContent.getAuth() == 4) {//
                            iv_auth_img.setImageDrawable(getResources().getDrawable(R.mipmap.icon_trend_onlyself));
                            tv_auth_name.setText("仅自己可见");
                        } else {
                            ll_auth.setVisibility(View.GONE);
                        }
                        if (communityContent.getTop() == 1) {
                            stv_top.setVisibility(View.VISIBLE);
                        } else {
                            stv_top.setVisibility(View.GONE);
                        }
                    } else {
                        ll_auth.setVisibility(View.GONE);
                        if (result.getResult().isFollow() == 1) {//已关注
                            stv_focus.setVisibility(View.GONE);
                            stv_focused.setVisibility(View.VISIBLE);
                        } else {
                            stv_focus.setVisibility(View.VISIBLE);
                            stv_focused.setVisibility(View.GONE);
                        }
                        stv_focus.setVisibility(View.GONE);//订阅隐藏
                        stv_focused.setVisibility(View.GONE);
                    }

                    if (result.getResult().getFileType() == 1) {//图片
                        if (!TextUtils.isEmpty(result.getResult().getFiles())) {
                            if (result.getResult().getFiles().contains(",")) {//多张
                                mData.clear();
                                recyclerView.setVisibility(View.VISIBLE);
                                siv_signle_img.setVisibility(View.GONE);
                                iv_play.setVisibility(View.GONE);

                                PicAdapter mAdapter = new PicAdapter();
                                recyclerView.setAdapter(mAdapter);
                                mData.addAll(MyUtils.toList(result.getResult().getFiles()));
                                mAdapter.setData();

                                recyclerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                        imagesMediaList.clear();

                                        for (int i = 0; i < MyUtils.toList(result.getResult().getFiles()).size(); i++) {
                                            LocalMedia localMedia = new LocalMedia();
                                            localMedia.setPath(MyUtils.toList(result.getResult().getFiles()).get(i));
                                            imagesMediaList.add(localMedia);
                                        }
                                        preView(position);
//                                        startActivity(new Intent(CommentDetailActivity.this, PreViewImgOrVideoActivity.class)
//                                                .putExtra("type", result.getResult().getFileType())
//                                                .putExtra("url", result.getResult().getFiles()));
                                    }
                                });

                            } else {
                                recyclerView.setVisibility(View.GONE);
                                siv_signle_img.setVisibility(View.VISIBLE);
                                iv_play.setVisibility(View.GONE);

                                loadImage(result.data.getFiles(), siv_signle_img);
                                siv_signle_img.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        imagesMediaList.clear();
                                        LocalMedia localMedia = new LocalMedia();
                                        localMedia.setPath(result.getResult().getFiles());
                                        imagesMediaList.add(localMedia);
                                        preView(0);

//                                        startActivity(new Intent(CommentDetailActivity.this, PreViewImgOrVideoActivity.class)
//                                                .putExtra("type", result.getResult().getFileType())
//                                                .putExtra("url", result.getResult().getFiles()));
                                    }
                                });
                            }

                        }
                    } else if (result.getResult().getFileType() == 2) {//视频
                        recyclerView.setVisibility(View.GONE);
                        siv_signle_img.setVisibility(View.VISIBLE);
                        iv_play.setVisibility(View.VISIBLE);

                        try {
                            MyUtils.getVideoThumbnail(CommentDetailActivity.this, result.getResult().getFiles(), siv_signle_img);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        siv_signle_img.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                startActivity(new Intent(CommentDetailActivity.this, PreViewImgOrVideoActivity.class)
                                        .putExtra("type", result.getResult().getFileType())
                                        .putExtra("url", result.getResult().getFiles()));
                            }
                        });
                    } else {
                        recyclerView.setVisibility(View.GONE);
                        siv_signle_img.setVisibility(View.GONE);
                        iv_play.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtils.showToast(result.msg);
                    finish();
                }
//                socialCircleViewModel.getCommunityInfo().removeObserver(this);

            }
        });

        socialCircleViewModel.getCommentList().observe(CommentDetailActivity.this, new Observer<Result2<BaseResultCommentListBean>>() {
            @Override
            public void onChanged(Result2<BaseResultCommentListBean> result) {
                if (result.code == 200) {
                    if (refreshList.isRefreshing()) {
                        refreshList.finishRefresh();
                    }
                    if (result.data != null && result.data.getList().size() > 0) {
                        if (page == 1) {
                            listAdapter.setNewInstance(result.data.getList());
                        } else {
                            if (result.data.getList().size() > 0) {
                                listAdapter.addData(result.data.getList());
                                refreshList.setEnableLoadMore(true);
                            } else {
                                refreshList.setEnableLoadMore(false);
//                            listAdapter.getLoadMoreModule().loadMoreEnd(false);
//                            listAdapter.getLoadMoreModule().loadMoreComplete();
                                refreshList.finishLoadMoreWithNoMoreData();
                            }
                        }
                        listAdapter.notifyDataSetChanged();
                    }
                }
//                socialCircleViewModel.getCommentList().removeObserver(this);

            }
        });

    }

    private List<String> titleList = new ArrayList<>();
    private final ArrayList<LocalMedia> imagesMediaList = new ArrayList<>();

    private void preView(int position) {
        // 预览图片、视频、音频
        PictureSelector.create(this)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .isPreviewFullScreenMode(true)
//                .isPreviewZoomEffect(true, recyclerView)
                .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                    @Override
                    public void onPreviewDelete(int position) {

                    }

                    @Override
                    public boolean onLongPressDownload(Context context, LocalMedia media) {
                        return false;
                    }
                })
                .startActivityPreview(position, false, imagesMediaList);
    }

    private void initView() {
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        listAdapter = new CommentListAdapter(2, this);
        listAdapter.setEmptyView(View.inflate(this, R.layout.empty_data_layout, null));
        rv_list.setAdapter(listAdapter);
        listAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                titleList.clear();
                if ((listAdapter.getData().get(position).getUserId() + "").equals(IMManager.getInstance().getCurrentId())) {
                    titleList.add("回复");
                    titleList.add("复制");
                    titleList.add("删除");
                } else {
                    titleList.add("回复");
                    titleList.add("复制");
                }
                new XPopup.Builder(CommentDetailActivity.this)
                        .dismissOnTouchOutside(true)
                        .dismissOnBackPressed(true)
                        .asBottomList("", titleList.toArray(new String[0]), new OnSelectListener() {
                            @Override
                            public void onSelect(int pos, String text) {
                                if (text.equals("复制")) {
                                    MyUtils.copyTextToClipboard(CommentDetailActivity.this, listAdapter.getData().get(position).getContent());
                                    ToastUtils.showToast("复制成功");
                                } else if (text.equals("回复")) {
                                    ll_bottom.setVisibility(View.GONE);
                                    popComment(2, listAdapter.getData().get(position).getUserId() + "", "", listAdapter.getData().get(position).getId() + "");
                                } else if (text.equals("删除")) {
                                    socialCircleViewModel.delComment(listAdapter.getData().get(position).getId() + "");
                                    socialCircleViewModel.delComment().observe(CommentDetailActivity.this, new Observer<Result2<String>>() {
                                        @Override
                                        public void onChanged(Result2<String> result) {
                                            if (result.code == 200) {
                                                ll_bottom.setVisibility(View.VISIBLE);
                                                ToastUtils.showToast("删除成功");
                                                if (popupView != null) {
                                                    popupView.dismiss();
                                                }
                                                initDate();
                                            } else {
                                                ToastUtils.showToast(result.msg);
                                            }
//                                            socialCircleViewModel.delComment().removeObserver(this);

                                        }
                                    });
                                }
                            }
                        })
                        .show();
            }
        });
        listAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_like:
                        int type = 0;
                        if (listAdapter.getData().get(position).isLiked() == 1) {//已点赞
                            type = 0;
                        } else {
                            type = 1;
                        }
                        isLikedComment(listAdapter.getData().get(position).getId() + "", IMManager.getInstance().getCurrentId(), type, 2, listAdapter.getData().get(position).getUserId() + "");
                        break;
                }
            }
        });

        refreshList.resetNoMoreData();
        refreshList.setRefreshHeader(new MaterialHeader(this));
        refreshList.setRefreshFooter(new ClassicsFooter(this));
        refreshList.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                socialCircleViewModel.getCommentList(getIntent().getStringExtra("id"), page, 10);
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                listAdapter.setNewInstance(null);
                socialCircleViewModel.getCommentList(getIntent().getStringExtra("id"), page, 10);
            }
        });

        stv_focus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("followerUserId", communityContent.getUserId());
                map.put("isFollower", 1);//1:订阅 0：取消订阅
                map.put("userId", IMManager.getInstance().getCurrentId());
                viewModel.createFollower(map, new Function1<BaseResultEntity<Object>, Unit>() {
                    @Override
                    public Unit invoke(BaseResultEntity<Object> result) {
                        if (result.getCode() == 200) {
                            socialCircleViewModel.getCommunityInfo(getIntent().getStringExtra("id"), IMManager.getInstance().getCurrentId());
                        } else {
                            ToastUtils.showToast(result.getMsg());
                        }
                        return null;
                    }
                });
            }
        });
        stv_focused.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("followerUserId", communityContent.getUserId());
                map.put("isFollower", 0);//1:订阅 0：取消订阅
                map.put("userId", IMManager.getInstance().getCurrentId());
                viewModel.createFollower(map, new Function1<BaseResultEntity<Object>, Unit>() {
                    @Override
                    public Unit invoke(BaseResultEntity<Object> result) {
                        if (result.getCode() == 200) {
                            socialCircleViewModel.getCommunityInfo(getIntent().getStringExtra("id"), IMManager.getInstance().getCurrentId());
                        } else {
                            ToastUtils.showToast(result.getMsg());
                        }
                        return null;
                    }
                });
            }
        });
        iv_like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int type = 0;
                if (communityContent.isLiked() == 1) {//已点赞
                    type = 0;
                } else {
                    type = 1;
                }
                isLikedComment(getIntent().getStringExtra("id"), IMManager.getInstance().getCurrentId(), type, 1, communityContent.getUserId() + "");
            }
        });
        iv_like_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int type = 0;
                if (communityContent.isLiked() == 1) {//已点赞
                    type = 0;
                } else {
                    type = 1;
                }
                isLikedComment(getIntent().getStringExtra("id"), IMManager.getInstance().getCurrentId(), type, 1, communityContent.getUserId() + "");
            }
        });
        stv_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ll_bottom.setVisibility(View.GONE);
                popComment(1, communityUserid + "", "", "");
            }

        });

    }

    private void isLikedComment(String busId, String userId, int isLiked, int types, String bdzUserId) {// types 1动态2评论

        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("busId", busId);
        paramsMap.put("userId", userId);
        paramsMap.put("type", types);//1动态2评论
        paramsMap.put("isLiked", isLiked);//1:点赞 0：取消
        paramsMap.put("bdzUserId", bdzUserId);//被点赞用户id,communityContent.getUserId()
        RequestBody body = RetrofitUtil.createJsonRequest(paramsMap);
        socialCircleViewModel.commentLiked(body);
        socialCircleViewModel.commentLiked().observe(CommentDetailActivity.this, new Observer<Result2<String>>() {
            @Override
            public void onChanged(Result2<String> result) {
                if (result.code == 200) {
                    initDate();
//                            if (finalType == 1) {
                    ToastUtils.showToast("操作成功");
//                            } else {
//                                ToastUtils.showToast("取消点赞成功");
//                            }
                } else {
                    ToastUtils.showToast(result.msg);
                }
//                socialCircleViewModel.commentLiked().removeObserver(this);

            }
        });
    }


    private void popComment(int type, String commentedUserId, String commentedNickname, String parentId) {//1：评论 2：回复
        popupView = new XPopup.Builder(CommentDetailActivity.this)
                .setPopupCallback(new XPopupCallback() {
                    @Override
                    public void onCreated(BasePopupView popupView) {

                    }

                    @Override
                    public void beforeShow(BasePopupView popupView) {

                    }

                    @Override
                    public void onShow(BasePopupView popupView) {

                    }

                    @Override
                    public void onDismiss(BasePopupView popupView) {
                        ll_bottom.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void beforeDismiss(BasePopupView popupView) {

                    }

                    @Override
                    public boolean onBackPressed(BasePopupView popupView) {
                        return false;
                    }

                    @Override
                    public void onKeyBoardStateChanged(BasePopupView popupView, int height) {

                    }

                    @Override
                    public void onDrag(BasePopupView popupView, int value, float percent, boolean upOrLeft) {

                    }

                    @Override
                    public void onClickOutside(BasePopupView popupView) {

                    }
                })
                .dismissOnTouchOutside(true)
                .dismissOnBackPressed(true)
                .asCustom(new CommentPopup(CommentDetailActivity.this, 1, new CommentPopup.onClick() {
                    @Override
                    public void uploadImg(@NonNull String s3, @NonNull String s4) {
                        userInfoViewModel.uploadImg(s3);
                        userInfoViewModel.upload().observe(CommentDetailActivity.this, new Observer<Resource2<String>>() {
                            @Override
                            public void onChanged(Resource2<String> resource) {

                                if (resource.status == Status.SUCCESS && resource.data != null) {
                                    commentImg = resource.data;
                                    Log.e("commentImg", commentImg);
                                }
//                                userInfoViewModel.upload().removeObserver(this);

                            }
                        });

                    }

                    @Override
                    public void click(@NonNull String content, @NonNull String s1) {
                        HashMap<String, Object> paramsMap = new HashMap<>();
                        paramsMap.put("contentId", communityContent.getId());
                        paramsMap.put("content", content);
                        paramsMap.put("type", type);//1：评论 2：回复
                        paramsMap.put("imgUrl", commentImg);
                        paramsMap.put("commentedNickname", commentedNickname);
                        paramsMap.put("commentedUserId", commentedUserId);//被评论人userid,
                        paramsMap.put("parentId", parentId);//评论id
                        RequestBody body = RetrofitUtil.createJsonRequest(paramsMap);
                        socialCircleViewModel.createComment(body);
                        socialCircleViewModel.createComment().observe(CommentDetailActivity.this, new Observer<Result2<CommunityContent>>() {
                            @Override
                            public void onChanged(Result2<CommunityContent> result) {

                                if (result.code == 200) {
                                    ll_bottom.setVisibility(View.VISIBLE);
                                    ToastUtils.showToast("评论成功");
                                    if (popupView != null) {
                                        popupView.dismiss();
                                    }

                                    initDate();
                                } else {
                                    ToastUtils.showToast(result.msg);
                                }
//                                socialCircleViewModel.createComment().removeObserver(this);

                            }
                        });
                    }
                }));
        popupView.show();
    }


    private void initDate() {

        socialCircleViewModel.getCommunityInfo(getIntent().getStringExtra("id"), IMManager.getInstance().getCurrentId());
        socialCircleViewModel.getCommentList(getIntent().getStringExtra("id"), page, 10);

    }

    private void editVisible() {
        List<String> visibleList = new ArrayList<>();
        visibleList.add("全部可见");//1 2 3 4
        visibleList.add("仅订阅者可见");
        visibleList.add("只给谁看");
        visibleList.add("仅自己可见");
        new XPopup.Builder(CommentDetailActivity.this)
                .dismissOnTouchOutside(true)
                .dismissOnBackPressed(true)
                .asBottomList("", visibleList.toArray(new String[0]), new OnSelectListener() {
                    @Override
                    public void onSelect(int pos, String text) {
                        int auth = pos + 1;
                        if (pos == 2) {
                            //选择好友
                            startActivityForResult(
                                    new Intent(CommentDetailActivity.this, SelectSomeFriendActivity.class), 100);
                        } else {
                            HashMap<String, Object> map = new HashMap<>();
                            map.put("id", communityContent.getId());
                            map.put("auth", auth);
                            map.put("visibleIds", communityContent.getVisibleIds());
                            viewModel.appUpdateContent(map, new Function1<BaseResultEntity<Object>, Unit>() {
                                @Override
                                public Unit invoke(BaseResultEntity<Object> result) {
                                    if (result.getCode() == 200) {
                                        ToastUtils.showToast("操作成功");
                                        finish();
                                    } else {
                                        ToastUtils.showToast(result.getMsg());
                                    }
                                    return null;
                                }
                            });
                        }
                    }
                })
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    List<String> memberList = data.getStringArrayListExtra(IntentExtra.LIST_STR_ID_LIST);
                    SLog.i("PublishCommunityActivity", "memberList.size = " + memberList.size());
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("id", communityContent.getId());
                    map.put("auth", 3);
                    map.put("visibleIds", memberList);
                    viewModel.appUpdateContent(map, new Function1<BaseResultEntity<Object>, Unit>() {
                        @Override
                        public Unit invoke(BaseResultEntity<Object> result) {
                            if (result.getCode() == 200) {
                                ToastUtils.showToast("操作成功");
                                finish();
                            } else {
                                ToastUtils.showToast(result.getMsg());
                            }
                            return null;
                        }
                    });
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (popupView != null) {
            popupView.onDestroy();
        }
    }

    @Override
    public void onItemClick(int position, @Nullable CommentChildren data) {
        titleList.clear();
        if ((data.getUserId() + "").equals(IMManager.getInstance().getCurrentId())) {
            titleList.add("回复");
            titleList.add("复制");
            titleList.add("删除");
        } else {
            titleList.add("回复");
            titleList.add("复制");
        }
        new XPopup.Builder(CommentDetailActivity.this)
                .dismissOnTouchOutside(true)
                .dismissOnBackPressed(true)
                .asBottomList("", titleList.toArray(new String[0]), new OnSelectListener() {
                    @Override
                    public void onSelect(int pos, String text) {
                        if (text.equals("复制")) {
                            MyUtils.copyTextToClipboard(CommentDetailActivity.this, data.getContent());
                            ToastUtils.showToast("复制成功");
                        } else if (text.equals("回复")) {
                            ll_bottom.setVisibility(View.GONE);
                            popComment(2, data.getUserId() + "", data.getNickname() + "", listAdapter.getData().get(position).getId() + "");
                        } else if (text.equals("删除")) {
                            socialCircleViewModel.delComment(data.getId() + "");
                            socialCircleViewModel.delComment().observe(CommentDetailActivity.this, new Observer<Result2<String>>() {
                                @Override
                                public void onChanged(Result2<String> result) {

                                    if (result.code == 200) {
                                        ll_bottom.setVisibility(View.VISIBLE);
                                        ToastUtils.showToast("删除成功");
                                        if (popupView != null) {
                                            popupView.dismiss();
                                        }
                                        initDate();
                                    } else {
                                        ToastUtils.showToast(result.msg);
                                    }
//                                    socialCircleViewModel.delComment().removeObserver(this);

                                }
                            });
                        }
                    }
                })
                .show();
    }

    @Override
    public void onItemChildClick(int position, @Nullable CommentChildren data) {
        int type = 0;
        if (data.isLiked() == 1) {//已点赞
            type = 0;
        } else {
            type = 1;
        }
        isLikedComment(data.getId() + "", IMManager.getInstance().getCurrentId(), type, 2, data.getUserId() + "");
    }

    private class PicAdapter extends BaseAdapter {
        private List<Uri> mUris;
        private List<String> mPaths;
        ViewHolder viewHolder;

        private void setData(List<Uri> uris, List<String> paths) {
            mUris = uris;
            mPaths = paths;
            notifyDataSetChanged();
        }

        private void setData() {
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            if (mData == null) return 0;
            else
                return mData.size();

        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                viewHolder = new ViewHolder();
                // 由于我们只需要将XML转化为View，并不涉及到具体的布局，所以第二个参数通常设置为null
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_grid_picture, null);

                //对viewHolder的属性进行赋值
                viewHolder.img_url = (RadiusImageView) convertView.findViewById(R.id.img_url);
                viewHolder.deleteImg = (ImageView) convertView.findViewById(R.id.delete_picture);

                //通过setTag将convertView与viewHolder关联
                convertView.setTag(viewHolder);
            } else {//如果缓存池中有对应的view缓存，则直接通过getTag取出viewHolder
                viewHolder = (ViewHolder) convertView.getTag();
            }

            viewHolder.deleteImg.setVisibility(View.GONE);
            loadImage(mData.get(position), viewHolder.img_url);

            return convertView;
        }

        class ViewHolder {
            public RadiusImageView img_url;
            public ImageView deleteImg;
        }
    }
}